<template>
  <div class="cost-summary">
    <ProTable ref="business_table_ref" :immediate="true" :pagination="true" :search-form="formList" :columns="columns"
      :request="queryBusinessPage" :onRequestSuccess="requestSuccessCallback">
      <template #extra>

        <Authc permissions="trade:merchant:business:add">
          <Button type="primary" @click="openBusinessModel()">添加</Button>
        </Authc>
      </template>
    </ProTable>

    <!-- 编辑弹窗 -->
    <Modal v-model="isShow" :visible.sync="isShow" :title="title">
      <Loading :loading="false">
        <Form ref="dataModule" :label-width="130" :model="business" :rules="ruleValidate">

          <FormItem prop="businessName" label="业务名称：">
            <Input type="text" v-model.trim="business.businessName" placeholder="请填写,长度不超多32" clearable />
          </FormItem>
          <FormItem label="业务图标：">
            <Input type="textarea" v-model="business.iconUrl" placeholder="请填写" show-word-limit maxlength="200"
              clearable />
          </FormItem>
        </Form>
      </Loading>
      <div slot="footer">
        <Button style="margin-left: 8px" @click="handleSubmitCancel('dataModule')">取消</Button>
        <Button type="primary" @click="handleSubmit('dataModule')">确定</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import ProTable from '@/components/ProTable';
import { queryBusinessPage, queryById, addBusiness, updateBusiness, deleteBusiness } from '@/api/merchant';
import Loading from "@/components/Loading";
import util from '@/utils/util'
import Authc from "@/components/Authc";
import { resolveComponent } from 'vue';

export default {
  name: 'BusinessTableRef',
  components: {
    ProTable,
    Authc,
    Loading
  },
  data() {
    return {
      title: '业务管理',
      isShow: false,
      exportSection: [],
      selectExportSectionItem: {},
      business: {
        id: null,
        businessName: null,
        businessCode: null,
        iconUrl: null,
        createdDt: null,
      },
      ruleValidate: {
        businessName: [{ required: true, message: '业务名称不能为空', trigger: 'blur' }]
      },
      formList: [
        {
          type: 'input',
          name: 'businessName',
          label: '业务名称',
        },

      ],
      columns: [
        {
          title: '业务名称',
          key: 'businessName',
          align: 'center',
        },
        {
          title: '业务编码',
          key: 'businessCode',
          align: 'center',
        },
        {
          title: '图标链接',
          key: 'iconUrl',
          align: 'center',
        },
        {
          title: '操作',
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h('A', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.openBusinessModel(params.row)
                  }
                }
              }, '修改'),
              h('A', {
                props: {
                  type: 'error',
                  size: 'small'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.deleteItem(params.row.id)
                  }
                }
              }, '删除')
            ])
          }
        },
      ]
    };
  },
  created() {
  },
  methods: {
    queryBusinessPage,
    async selectExportSection(item) {
      this.selectExportSectionItem = item
    },
    //查询成功回调
    async requestSuccessCallback(res) {
      if (res && res.data.pagination) {
        const total = res.data.pagination.total || 0
        if (total) {
          const sections = Math.ceil(total / 5000)
          let newExportSection = []
          for (let i = 1; i <= sections; i++) {
            newExportSection.push({
              id: i,
              start: (i - 1) * 5000 === 0 ? 1 : (i - 1) * 5000,
              end: i * 5000
            })
          }
          console.log(this.exportSection)
          this.exportSection = newExportSection
        } else {
          this.exportSection = []
        }
      } else {
        this.exportSection = []
      }
    },

    async openBusinessModel(params) {
      if (params && params.id) {
        const { data: { ret, data } } = await queryById(params.id)
        this.business = data
        this.addtype = "update"
      } else {
        this.addtype = "add"
      }
      this.isShow = true

    },

    handleSubmitCancel(formName) {
      this.isShow = false
      this.$refs[formName].resetFields()
    },
    async handleSubmit(name) {
      let that = this
      that.$refs[name].validate(async valid => {
        if (valid) {
          if (that.addtype === 'add') {
            await addBusiness(this.business)

          } else {
            await updateBusiness(this.business)
          }
          that.$refs.business_table_ref.onSearch();
          that.isShow = false;

        } else {
          console.log('error submit!!')
          // return false
        }
      })
    },
    // 重置
    resetForm() {
      if (this.$refs['dataModule'].fields) {
        this.$refs['dataModule'].fields.forEach(function (e) {
          if (e.prop == 'businessName') e.resetField();
        })
      }
    },

    async deleteItem(id) {
      const that = this
      this.$Modal.confirm({
        title: '提示',
        content: '是否确认删除该业务类型？',
        onOk: async () => {
          await deleteBusiness(id)
          that.$refs.business_table_ref.onSearch();
        },
        onCancel: () => {
        }
      });

    }
  }
};
</script>

<style>
.selectSectionItem {
  color: #2b85e4;
}
</style>
